package com.bingfor.easycablelink.base;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.StringRes;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;


import com.bingfor.easycablelink.R;
import com.bingfor.easycablelink.utils.ActivityUtil;
import com.bingfor.easycablelink.utils.DeviceUtils;
import com.bingfor.easycablelink.utils.DialogHelp;
import com.bingfor.easycablelink.utils.ToastUtil;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import rx.Subscription;


/**
 * Created by Modificator
 * Date: 2016/2/16
 * Time: 15:53
 * Connect: yunshangcn@gmail.com
 */
public abstract class BaseActivity extends RxAppCompatActivity {

    public ProgressDialog waitDialog;
    protected BaseActivity mContext;
    protected boolean isPause = true;
    public View rootView;
    public static int statusBarHeight = 0;
    public Map<String, Subscription> scriptionList = new HashMap<>();




    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        ActivityUtil.getAppManager().addActivity(this);
        waitDialog = DialogHelp.getWaitDialog(mContext, "正在提交...");
        waitDialog.setCancelable(false);
        if (statusBarHeight < 10) {
            statusBarHeight = DeviceUtils.getStatusBarHeight(mContext);
        }
        setStatusBar();
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void setStatusBar() {
        Window window = mContext.getWindow();
    //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

    //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    //设置状态栏颜色
        window.setStatusBarColor(getResources().getColor(R.color.red));

        ViewGroup mContentView = (ViewGroup) mContext.findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
            ViewCompat.setFitsSystemWindows(mChildView, true);
        }
    }
        @Override
        public void setContentView ( @LayoutRes int layoutResID){
            this.setContentView(getLayoutInflater().inflate(layoutResID, null));
        }

        @Override
        public void setContentView (View view){
            this.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }

        @Override
        public void setContentView (View view, ViewGroup.LayoutParams params){
            //super.setContentView(view instanceof ViewGroup ? (ViewGroup)view : view , params);
            super.setContentView(rootView = view, params);

        }

    /**
     * 在此初始化View
     */
    public abstract void initViews();

    /**
     * 在此初始化Toolbar,以及处理intent里面的数据
     */
    public abstract void initToolbar();

    /**
     * 统一调用数据更新入口
     */
    public abstract void refresh();


    /**
     * 设置标题
     *
     * @param title
     */
    protected void setTitle(String title) {
        Toolbar tvTitle = $(R.id.toolbar);
        if (tvTitle != null) {
            tvTitle.setTitle(title);
        }
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(title);
        }
        super.setTitle(title);
    }

    protected void showToolbarBack() {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    /**
     * {@link AppCompatActivity#onResume()}
     */
    @Override
    protected void onResume() {
        super.onResume();
        mContext = this;
        isPause = false;
        //注：回调 1
//        Bugtags.onResume(this);
    }

    /**
     * {@link AppCompatActivity#onPause()}
     */
    @Override
    protected void onPause() {
        super.onPause();
        isPause = true;
        //注：回调 2
//        Bugtags.onPause(this);
    }

    /**
     * 开启新的activity,防止activity未注册或 启动失败
     *
     * @param intent
     */
    @Override
    public void startActivity(Intent intent) {
        try {
            super.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void finish() {
        super.finish();
        mContext = null;
        isPause = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
//        mContext = null;
        isPause = true;
    }

    @Override
    protected void onDestroy() {
        isPause = true;
        super.onDestroy();
        mContext = null;
        // 结束Activity&从堆栈中移除
        ActivityUtil.getAppManager().finishActivity(this);
    }

    /**
     * 跳转actiivty
     *
     * @param c      要跳转的activity class
     * @param bundle 跳转时传递的参数
     */
    public void moveToNextPage(@NonNull Class<?> c, Bundle bundle) {
        moveToNextPage(c, bundle, 0);
    }

    /**
     * 跳转activity class
     *
     * @param c      要跳转的activity class
     * @param bundle 跳转时传递的参数
     * @param flags  The desired flags.{@link Intent#setFlags(int)}
     */
    public void moveToNextPage(@NonNull Class<?> c, Bundle bundle, int flags) {
        moveToNextPage(c, bundle, false, flags);
    }

    /**
     * 跳转activity class
     *
     * @param c      要跳转的activity class
     * @param bundle 跳转时传递的参数
     * @param b      是否需要继续传递前一个页面传过来的参数
     * @param flags  The desired flags.{@link Intent#setFlags(int)}
     */
    public void moveToNextPage(@NonNull Class<?> c, Bundle bundle, boolean b, int flags) {
        Intent intent;
        if (!b)
            intent = new Intent();
        else
            intent = getIntent();
        intent.setClass(mContext, c);
        if (bundle != null)
            intent.putExtras(bundle);
        if (flags > 0)
            intent.setFlags(flags);
        startActivity(intent);
    }

    /**
     * 跳转activity class
     *
     * @param c 要跳转的activity class
     */
    public void moveToNextPage(Class<?> c) {
        moveToNextPage(c, null);
    }

    /**
     * 跳转activity class
     *
     * @param c     要跳转的activity class
     * @param flags The desired flags.{@link Intent#setFlags(int)}
     */
    public void moveToNextPage(Class<?> c, int flags) {
        moveToNextPage(c, null, flags);
    }


    /**
     * 获取View对象
     *
     * @param id  View的ID
     * @param <T>
     * @return
     */
    public <T extends View> T $(int id) {
        return (T) findViewById(id);
    }

    /**
     * 获取View对象
     *
     * @param id  View的ID
     * @param <T>
     * @return
     */
    public <T extends View> T getView(int id) {
        return $(id);
    }

    /**
     * 设置右上角返回键的时间处理
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        /*int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return false;
        }*/
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    public Context getContext() {
        return mContext;
    }

    @Override
    public void onBackPressed() {
//        DeviceUtils.closeKeyBoard(this);
        super.onBackPressed();
    }

    protected void unSubscribeAll() {
        for (String key : scriptionList.keySet()) {
            Subscription tmpSubscription = scriptionList.get(key);
            if (tmpSubscription.isUnsubscribed()) {
                tmpSubscription.unsubscribe();
                scriptionList.remove(key);
            }
        }
    }

    protected void unSubscribe(String... keys) {
        for (String key : scriptionList.keySet()) {
            Subscription tmpSubscription = scriptionList.get(key);
            if (Arrays.asList(keys).contains(key))
                if (tmpSubscription.isUnsubscribed()) {
                    tmpSubscription.unsubscribe();
                    scriptionList.remove(key);
                }
        }
    }

    public void showSnakeBar(String text) {
        SnackbarManager.show(
                Snackbar.with(mContext)
                        .text(text)
                        .textColor(0xffcdcdcd)
                        .color(0xff222222)
                        .duration(1)    )
                        ;

    }




    public void showWaitDialog(String message) {
        if (waitDialog == null)
            waitDialog = new ProgressDialog(mContext);
        waitDialog.setCanceledOnTouchOutside(false);
        waitDialog.setMessage(message);
        if (!waitDialog.isShowing())
            waitDialog.show();
    }


    public void showWaitDialog() {
        showWaitDialog("正在加载...");
    }


    public void dismissWaitDialog() {
        waitDialog.dismiss();
    }

    long maxProgress = 100;
    ProgressDialog progressDialog;


    public void showProgressDialog(String title, String message, long maxProgress, long progress) {
        if (progressDialog == null || !progressDialog.isShowing()) {
            progressDialog = new ProgressDialog(mContext);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        }
        if (title != null && title.length() > 0)
            progressDialog.setTitle(title);
        if (message != null && message.length() > 0)
            progressDialog.setMessage(message);
        progressDialog.setMax((int) (maxProgress == 0 ? progress > 100 ? progress : this.maxProgress : maxProgress));
        progressDialog.setProgress((int) progress);
        progressDialog.show();
    }


    public void showProgressDialog(String title, long maxProgerss, long progerss) {
        showProgressDialog(title, null, maxProgerss, progerss);
    }


    public void showProgressDialog(long maxProgerss, long progerss) {
        showProgressDialog(null, maxProgerss, progerss);
    }


    public void showProgressDialog(long progerss) {
        showProgressDialog(0, progerss);
    }


    public void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
    }

    public void showShortToast(String message) {
        ToastUtil.showToast(mContext, message);
    }


    public void showShortToast(@StringRes int resId) {
        showShortToast(getString(resId));
    }


    public void showLongToast(String message) {
        ToastUtil.showToast(mContext, message);
    }


    public void showLongToast(@StringRes int resId) {
        showLongToast(getString(resId));
    }



}
